package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.tbit.Version;
import com.tbit.config.query.LambdaQueryWrapperX;
import com.tbit.uqbike.constant.Constants;
import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.object.pojo.PlatformConfig;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.webmanager.dao.core.PlatformConfigDao;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.file.FileUtils;
import com.tbit.utils.Assert;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author jing
 */
@RestController
public class CommonController {
    @Autowired
    private PlatformConfigDao platformConfigDao;
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    public static void main(String[] args) {
        String url = "https://gxcxapp.oss-cn-hangzhou.aliyuncs.com/version/共享平台1.json";
        String body = HttpRequest.get(url).execute().body();
        System.out.println(body);
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName= "";
            if (fileName.contains("~")){
                realFileName = fileName.substring(fileName.indexOf("_") + 1);
            }else {
                realFileName = DateUtil.today() + fileName.substring(fileName.indexOf("_") + 1);
            }

            String filePath = OperaPswConstant.PATH + fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = OperaPswConstant.PATH;
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 前端get请求，解决跨域问题
     *
     * @param url 请求地址
     * @return
     */
    @PostMapping("/common/request")
    public String request(String url, @RequestBody Map<String, Object> param) {
        return HttpRequest.get(url).form(param).execute().body();
    }

    /**
     * 获取apk下载地址
     *
     * @param url
     * @return
     */
    @GetMapping("/common/getMainAppDownloadAddress")
    public Result getMainAppDownloadAddress(String url) {
        log.info("请求参数{}", url);
        Assert.notNulls("参数有误", url);
        String host = "";
        String body = HttpRequest.get(url).execute().body();
        log.info("响应body{}", body);
        if (StringUtils.isNotEmpty(body)) {
            Object data = JSON.parseObject(body).get("AndroidVersion");
            if (data != null) {
                host = data.toString();
            }
        }
        String format = String.format("https://gxcxapp.oss-cn-hangzhou.aliyuncs.com/gxcx/wnyw-%s.apk", host);
        log.info("返回的url{}", format);
        return Result.success(format);
    }

    /**
     * 心跳检测
     *
     * @return
     */
    @RequestMapping(value = "/heartbeat")
    public String heartbeat() {
        return Version.getVersion();
    }


    /**
     * 获取平台配置
     * @param platformConfig 查询参数（可不传）
     * @return 平台配置
     */
    @GetMapping("/common/getPlatformConfig")
    public Result<PlatformConfig> getPlatformConfig(PlatformConfig platformConfig) {
        PlatformConfig data = platformConfigDao.selectOne(new LambdaQueryWrapperX<PlatformConfig>()
                .eqIfPresent(PlatformConfig::getId, platformConfig.getId())
                .eqIfPresent(PlatformConfig::getSugarCallbackUrl, platformConfig.getSugarCallbackUrl())
                .eqIfPresent(PlatformConfig::getMainName, platformConfig.getMainName())
                .eqIfPresent(PlatformConfig::getAMapKey, platformConfig.getAMapKey())
                .eqIfPresent(PlatformConfig::getTMapKey, platformConfig.getTMapKey())
                .eqIfPresent(PlatformConfig::getAMapSecurityJsCode, platformConfig.getAMapSecurityJsCode())
        );
        return Result.success(data);
    }

}
